from celery import Celery
from scanner import scan_static_page, scan_Ajax_content
from translator import TranslationProcessor
from db import update_task_status
from config import CELERY_BROKER_URL, CELERY_RESULT_BACKEND

app = Celery("dictionary_tasks", broker=CELERY_BROKER_URL, backend=CELERY_RESULT_BACKEND)

@app.task(bind=True, retry_backoff=True, max_retries=3)
def process_static_page(self, domain, page_url, task_id):
    try:
        dictionary = scan_static_page(page_url)
        update_task_status(task_id, "completed", dictionary_file=f"translations/pre_trans_{dictionary['hash']}.json")
        return dictionary
    except Exception as e:
        update_task_status(task_id, "failed", error=str(e))
        self.retry(countdown=60)  # 重试间隔 60 秒

@app.task
def process_Ajax_content(domain, page_url, task_id):
    try:
        dictionaries = scan_Ajax_content(page_url)
        for dictionary in dictionaries:
            update_task_status(task_id, "completed", dictionary_file=f"translations/pre_trans_{dictionary['hash']}.json")
        return dictionaries
    except Exception as e:
        update_task_status(task_id, "failed", error=str(e))
        raise

# 新增翻译任务
@app.task
def process_translation(pre_trans_file, task_id, target_lang='zh-cn'):
    try:
        processor = TranslationProcessor()
        trans_file = processor.process_dictionary(pre_trans_file, target_lang)
        update_task_status(task_id, "completed", dictionary_file=trans_file)
        return trans_file
    except Exception as e:
        update_task_status(task_id, "failed", error=str(e))
        raise